package SalesBooth;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jdbcutil.JDBCUtil;

public class FruitDao {
	Connection conn = null;
	PreparedStatement ps = null;
	
	public Integer insert(FruitModel model) {
		String sql = "insert into test.fruit(name,inve,unitPri)values(?,?,?)";
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, model.getName());
			ps.setDouble(2, model.getInve());
			ps.setDouble(3, model.getUnitPri());	
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return null;
	}
	public Integer update(FruitModel model) {
		StringBuffer sql = new StringBuffer("update test.fruit");
		List<Object> vals = appendSet(sql,model);
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql.toString());
			for (int i = 0; i < vals.size(); i++) {
				ps.setObject(i + 1, vals.get(i));
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return null;
	}
	
	private List<Object> appendSet(StringBuffer sql, FruitModel model) {
		sql.append(" set name = name ");
		List<Object> objs = new ArrayList<Object>();
		double inve = model.getInve();
		sql.append(",inve = ? ");
		objs.add(inve);
		double unitPri = model.getUnitPri();
		sql.append(",unitPri = ? ");
		objs.add(unitPri);

		String name = model.getName();
		sql.append("where name = ? ");
		objs.add(name);
		return objs;
	}
	
	public List<FruitModel> selectList(FruitModel model) {
		List<FruitModel> list = new ArrayList<>();
		StringBuffer sql = new StringBuffer("select name,inve,unitPri from test.fruit");
		List<Object> vals = appendWhere(sql, model);
		ResultSet rs = null;
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql.toString());
			if (vals.size() == 0) {
				rs = ps.executeQuery();
			} else {
				for (int i = 0; i < vals.size(); i++) {
					ps.setObject(i + 1, vals.get(i));		
				}
				rs = ps.executeQuery();
			}
			while (rs.next()) {
				FruitModel mod = new FruitModel();
				mod.setName(rs.getString("name"));
				mod.setInve(rs.getDouble("inve"));
				mod.setUnitPri(rs.getDouble("unitPri"));
				list.add(mod);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps, rs);
		}
		return list;
	}

	private List<Object> appendWhere(StringBuffer sql, FruitModel model) {
		sql.append(" where 1=1");
		List<Object> objs = new ArrayList<>();
		String name = model.getName();
		if (name != null && !name.trim().isEmpty()) {// !"".equals(code.trim())
			sql.append(" and name = ?");
			objs.add(name);
		}
		return objs;
	}
}
